#define _POSIX_C_SOURCE 199309
#include "ota_update.h"
#include <unistd.h>
#include <sys/stat.h>
#include <sys/reboot.h>
#include "log/log.h"
#include "ota_http.h"

static int ota_update_checkupdate ()
{
    int result;
    Version curr_ver = CURRENT_VERSION;
    Version ver;
    result = ota_http_getVersion(&ver);
    if(result != 0)
    {
        log_error("ota update check version failed");
        return -1;
    }
    if (curr_ver.major < ver.major)
    {
        return 0;
    }
    if (curr_ver.major > ver.major)
    {
        return -1;
    }
    if (curr_ver.minor < ver.minor)
    {
        return 0;
    }
    if (curr_ver.minor > ver.minor)
    {
        return -1;
    }
    if (curr_ver.patch < ver.patch)
    {
        return 0;
    }
    return -1;
}

void ota_update_run()
{
    int result;
    while (1)
    {
        log_debug("ota update start");
        result = ota_update_checkupdate();

        if (result == 0)
        {
            sleep(86400);
            continue;
        }

        log_debug("ota update downloading...");

        result = ota_http_downloadFirmware(TEMP_FIRMWARE);
        if (result < 0)
        {
            log_error("ota update download failed");
            sleep(3600);
            continue;
        }
        log_debug("ota update download success, rebooting...");
        // 更新完毕，重新启动开发版
        reboot(RB_AUTOBOOT);
    }
    
}